package com.bwie.system.exception;


import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
@Log4j2
public class GlobalExceptions {

    @ExceptionHandler(BusinessException.class)
    public Result bizException(BusinessException bizException){
       log.error("业务异常信息: : : {}",bizException.getMessage());
       return Result.error(bizException.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException){
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(allError->{
            String defaultMessage = allError.getDefaultMessage();
            stringBuilder.append(defaultMessage+";");
        });

        log.error("业务异常信息: : : {}",stringBuilder.toString());
        return Result.error(stringBuilder.toString());
    }
}
